package com.alibaba.citrus.cr.mn.order.center.common.util;

import com.alibaba.cz.base.tool.log.Log;
import org.springframework.util.StopWatch;

import java.util.Objects;

/**
 * @author zhangxiaorui
 * @ClassName StopWatchUtils
 * @description: StopWatch埋点工具
 * @date 2023/05/08 15:24
 * @version: 1.0
 */
public class StopWatchUtils {

    private static final Log log = Log.getLogger(StopWatchUtils.class);

    public static ThreadLocal<StopWatch> CURRENT_STOP_WATCH = new ThreadLocal<>();

    public static void start(String sequenceNo, String masterTaskName) {
        StopWatch stopWatch = CURRENT_STOP_WATCH.get();
        if (Objects.nonNull(stopWatch)) {
            if(!stopWatch.isRunning()) {
                stopWatch.start(masterTaskName);
                CURRENT_STOP_WATCH.set(stopWatch);
            }
            return;
        }
        StopWatch stopWatchNew = new StopWatch(sequenceNo);
        stopWatchNew.start(masterTaskName);
        CURRENT_STOP_WATCH.set(stopWatchNew);
    }

    public static void stop() {
        if (Objects.isNull(CURRENT_STOP_WATCH.get())) {
            return;
        }
        StopWatch stopWatch = CURRENT_STOP_WATCH.get();
        if(stopWatch.isRunning()) {
            stopWatch.stop();
        }
    }

    public static StopWatch clear() {
        StopWatch stopWatch = CURRENT_STOP_WATCH.get();
        if (Objects.isNull(stopWatch)) {
            return null;
        }

        if(stopWatch.isRunning()) {
            stopWatch.stop();
        }
        CURRENT_STOP_WATCH.remove();

        return stopWatch;
    }

    public static void print(String key) {
        StopWatch stopWatch = StopWatchUtils.clear();// 移除ThreadLocal中存储对象
        if (Objects.nonNull(stopWatch)) {
            log.info("{} stopWatch.getTotalTimeSeconds()={}", key, stopWatch.getTotalTimeSeconds());
            log.info("{} stopWatch.prettyPrint()={}", key, stopWatch.prettyPrint());
        }
    }
}
